package com.example.market.config;

import com.example.market.service.OrderService;
import com.example.market.service.SeckillProductService;
import com.example.market.util.RedisKey;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class SeckillOrderQueue {


    private OrderService orderService;

    private SeckillProductService seckillProductService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }
    @Autowired
    public void setSeckillProductService(SeckillProductService seckillProductService) {
        this.seckillProductService = seckillProductService;
    }

    @RabbitListener(queues = "seckill_order")
    public void insertOrder(Map map, Channel channel, Message message){
        String correlationId = message.getMessageProperties().getCorrelationId();
        if (Boolean.FALSE.equals(stringRedisTemplate.hasKey(RedisKey.SECKILL_RABBITMQ_ID + correlationId)))
            // redis中存在，表明此条消息已消费，请勿重复消费
            return;


        String seckillId = (String) map.get("seckillId");
        String userId = (String) map.get("userId");
        stringRedisTemplate.opsForValue().set(RedisKey.SECKILL_RABBITMQ_ID + correlationId, "1");
        Long seckillEndTime = seckillProductService.getEndTime(seckillId);
        stringRedisTemplate.expire(RedisKey.SECKILL_RABBITMQ_ID + correlationId, seckillEndTime - new Date().getTime(), TimeUnit.SECONDS); // 设置过期时间

        try {
            orderService.addSeckillOrder(seckillId, userId);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                stringRedisTemplate.delete(RedisKey.SECKILL_RABBITMQ_ID + correlationId);
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            } catch (IOException ioException) {
                ioException.printStackTrace();

            }
        }
    }
}
